package com.storeapp.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.storeapp.dao.DealOrderDao;
import com.storeapp.dao.ItemDao;
import com.storeapp.entity.domain.DealOrder;
import com.storeapp.entity.domain.Item;

@Component
@Transactional
public class DealOrderService {
	@Autowired
	private DealOrderDao dealOrderDao;
	@Autowired
	private ItemDao itemDao;

	@Transactional(readOnly = true)
	public DealOrder getDealOrder(Long id) {
		return dealOrderDao.get(id);
	}

	/*
	 * save deal order and its related items
	 */
	public void saveDealOrder(Long customerId, List<Item> items) {
		DealOrder order = new DealOrder(null, customerId);
		order.setPurchaseDate(new Date());
		double totalPrice = 0.00;
		for (Item item : items) {
			totalPrice += item.getQuantity() * item.getDiscount()
					* item.getPrice();
			item.setDealOrder(order);
		}
		order.setTotalPrice(totalPrice);
		order.setItems(items);
		dealOrderDao.save(order);
	}
	
	@Transactional(readOnly = true)
	public List<Item> listItemsByOrder(DealOrder order){
		List<Item> items = itemDao.findBy("dealOrder", order);
		return items;
	}
	
	public void deleteDealOrder(DealOrder entity) {
		dealOrderDao.delete(entity);
	}

	@Transactional(readOnly = true)
	public List<DealOrder> listAll() {
		return dealOrderDao.getAll();
	}

	public double calculateTotalPrice(List<Item> items) {
		double totalPrice = 0.00;
		for (Item item : items) {
			totalPrice += item.getQuantity() * item.getDiscount()
					* item.getPrice();
		}
		return totalPrice;
	}
}
